#include"LinpopHeaders.h"

    GtkWidget *nickname;
//    GtkWidget *gender;
    GtkWidget *age;
 //   GtkWidget *branch;
    GtkWidget *telephone;
    GtkWidget *birthday;
    GtkWidget *okbutton;
    GtkWidget *SettingSuc_Window;
    GtkWidget *SettingFail_Window;
    GtkWidget *SettingFail_Button;
    GtkWidget *SettingSuc_Button;
    GtkBuilder *settingfail_builder;
    GtkBuilder *settingsuc_builder;

    GtkWidget *Setting_GenderCBX;
    GtkWidget *Setting_BranchCBX;

    gchar mysetting[1024]={0};
    gchar myage[10]={0};
  //  gchar myprofilepic[10]={0};
   // const
pthread_t Setting_Listenthread_t;
char buf[1024];
//bzero(buf , 1024 );
int socket_setting_recv;
int socket_mainframe_listen_recv;

void on_settingsuc_Button_clicked(GtkObject *object,gpointer user_data)
{

    gtk_widget_hide(SettingSuc_Window);
    gtk_widget_hide(Setting_Window);
 //   pthread_cancel(Setting_Listenthread_t);
}
void on_settingfail_Button_clicked(GtkObject *object,gpointer user_data)
{

   gtk_widget_hide(SettingFail_Window);
    gtk_widget_hide(Setting_Window);
  //  pthread_cancel(Setting_Listenthread_t);
}
void on_servererror_Button_clicked(GtkObject *object,gpointer user_data)
{

   gtk_widget_hide(Servererror_Window);
    gtk_widget_hide((Setting_Window));
}

void  * Setting_Listenthread( void *arg )
{

    struct sockaddr_in socksetting_recv;

  //  int sock_len;

    bzero(&socksetting_recv, sizeof(socksetting_recv));
    socksetting_recv.sin_family = AF_INET;
    socksetting_recv.sin_addr.s_addr = INADDR_ANY;
    socksetting_recv.sin_port = htons(SETTINGPORT);
   // sock_len = sizeof(socksetting_recv);
    g_print("test2\n");
    if((socket_setting_recv = socket(AF_INET,SOCK_DGRAM,0)) == -1)                                                                     //接受注册成功/失败信息
        {
                perror("Socket_recv");
                exit(1);
        }
        else if (bind(socket_setting_recv,(struct sockaddr *)&socksetting_recv,sizeof(socksetting_recv)) == -1)
        {
                printf("Error in bind\n");
                exit(1);
                close(socket_setting_recv);
        }
        else
        {
                g_print("bind success\n");
                bzero(buf,sizeof(buf));
               // bzero(buf,sizeof(buf));

                    //if (recvfrom(socket_setting_recv,buf,sizeof(buf),0,(struct sockaddr*)&socksetting_recv, (socklen_t *)&sock_len) != -1)
                    if (recvfrom(socket_setting_recv,buf,sizeof(buf),0,NULL, NULL) != -1)
                    {
                        g_print("buf:%s\n",buf);
                        close(socket_setting_recv);

                    }


        }
        return (void *)0;
}
void modify_myinformation(GtkObject *object,gpointer user_data)
{
        gchar *Setting_Gender_CBX = NULL;
        gchar *Setting_Branch_CBX = NULL;

        bzero(myinformation.nickName,sizeof(myinformation.nickName));
       // bzero(myinformation.gender,sizeof(myinformation.gender));
       // bzero(myinformation.branch,sizeof(myinformation.branch));
        bzero(myinformation.telephone,sizeof(myinformation.telephone));
        bzero(myinformation.birthdate,sizeof(myinformation.birthdate));
        //myinformation.profilepic=0;
        myinformation.age=0;

        Setting_Gender_CBX = gtk_combo_box_get_active_text(GTK_COMBO_BOX(Setting_GenderCBX));
        Setting_Branch_CBX = gtk_combo_box_get_active_text(GTK_COMBO_BOX(Setting_BranchCBX));

        strcpy(myinformation.nickName,(gtk_entry_get_text(GTK_ENTRY(nickname))));
        strcpy(myinformation.gender ,Setting_Gender_CBX);
        strcpy(myage,(gtk_entry_get_text(GTK_ENTRY(age))));
        strcpy(myinformation.branch ,Setting_Branch_CBX);
        strcpy(myinformation.telephone ,(gtk_entry_get_text(GTK_ENTRY(telephone))));
        strcpy(myinformation.birthdate ,(gtk_entry_get_text(GTK_ENTRY(birthday))));
        myinformation.age = atoi(myage);



        int sendSockfd;
        struct sockaddr_in sin_addr;
        gchar myprofilepic[5];
        sendSockfd = socket(AF_INET, SOCK_DGRAM, 0);
        bzero(&sin_addr, sizeof(sin_addr));

        sin_addr.sin_family = AF_INET;
        sin_addr.sin_addr.s_addr = inet_addr(SERVERIP);
        sin_addr.sin_port = htons(SETTINGPORT);
        // g_print("test2");
        bzero(mysetting, sizeof(mysetting));
        sprintf(myprofilepic,"%d",myinformation.profilepic);

        mysetting[0] = '4';

        strcat(mysetting,"~");                                                                                                                                //组包
        strcat(mysetting,myinformation.senderName);
        g_print("sendername:%s \n",myinformation.senderName);
        strcat(mysetting,"~");
        //destName
        strcat(mysetting,"~");
        //passwd
        strcat(mysetting,"~");
        strcat(mysetting,myinformation.sourceIP);
        //sourceIP
        strcat(mysetting,"~");
        //destIP

        strcat(mysetting,"~");
        strcat(mysetting,myinformation.nickName);
        //nickname
        strcat(mysetting,"~");
        //strcat(mysetting,myinformation.state);
        //state
        strcat(mysetting,"~");
        strcat(mysetting,myinformation.gender);
        //strcat(mysetting,Register_GenderEntry_char);
        strcat(mysetting,"~");
        strcat(mysetting,(myage));
        strcat(mysetting,"~");
        strcat(mysetting,myinformation.branch);
        //strcat(mysetting,Register_DepartEntry_char);
        strcat(mysetting,"~");
        strcat(mysetting,myinformation.telephone);
        //tel
        strcat(mysetting,"~");
        strcat(mysetting,myinformation.birthdate);
        //birth
        strcat(mysetting,"~");
        strcat(mysetting,myprofilepic);
        //profilepic
        strcat(mysetting,"~");
        //msg
        //strcat(sendmessage,S_text);
        strcat(mysetting,"~");

        g_print("send information: %s",mysetting);
        if(sendto(sendSockfd, mysetting, strlen(mysetting)+1,0, (struct sockaddr *)&sin_addr, sizeof(sin_addr)) == -1)
        {
            perror("sendsocked");
            exit(0);
        }
            g_print("prepare to enter the pthread\n");
            close(sendSockfd);
            int test=10;
            bzero(buf,sizeof(buf));

            test=pthread_create(&Setting_Listenthread_t, NULL, Setting_Listenthread,NULL);
            g_print("test:%d \n",test);
            g_print("pthread_create success\n");
            int i = 0;
            for(i = 0; i < 300; i++)
            {
                if(buf[0] == '\0')
                {
            //               g_print("bieshuile\n");
                    usleep(10000);
                }
                else
                {
                    break;
                }
            }



            if(buf[0] == '\0')
            {
                //弹出服务器error窗口
                pthread_cancel(Setting_Listenthread_t);
                close(socket_setting_recv);
                Servererror_builder = gtk_builder_new();
                gtk_builder_add_from_file(Servererror_builder,"Servererror.glade",NULL);
                Servererror_Window = GTK_WIDGET(gtk_builder_get_object(Servererror_builder,"Servererror_Window"));
                Servererror_Button = GTK_WIDGET(gtk_builder_get_object(Servererror_builder,"Servererror_Button"));
                g_signal_connect(G_OBJECT(Servererror_Button),"clicked",G_CALLBACK(on_servererror_Button_clicked),NULL);
                gtk_builder_connect_signals(Servererror_builder,NULL);
                g_object_unref(G_OBJECT(Servererror_builder));
                gtk_widget_show(Servererror_Window);
                gtk_main();
                pthread_cancel(Setting_Listenthread_t);

                g_print("Server Error!\n");

            }
                else if(strcmp(buf,"error") == 0)
                        {
                            g_print("receive fail\n");
                            bzero(buf,sizeof(buf));
                            settingfail_builder = gtk_builder_new();
                            gtk_builder_add_from_file(settingfail_builder,"SettingFail.glade",NULL);

                            SettingFail_Window = GTK_WIDGET(gtk_builder_get_object(settingfail_builder,"SettingFail_Window"));
                            SettingFail_Button = GTK_WIDGET(gtk_builder_get_object(settingfail_builder,"SettingFail_Button"));
                            gtk_window_set_title (GTK_WINDOW (SettingFail_Window), "修改信息失败");

                            g_signal_connect(G_OBJECT(SettingFail_Button),"clicked",G_CALLBACK(on_settingfail_Button_clicked),NULL);

                            gtk_builder_connect_signals(settingfail_builder,NULL);
                            g_object_unref(G_OBJECT(settingfail_builder));
                            gtk_widget_show_all(SettingFail_Window);
                            gtk_main();
                        }
                         else if(strcmp(buf,"success") == 0)
                         {

                            settingsuc_builder = gtk_builder_new();
                            gtk_builder_add_from_file(settingsuc_builder,"SettingSuc.glade",NULL);
                            SettingSuc_Window = GTK_WIDGET(gtk_builder_get_object(settingsuc_builder,"SettingSuc_Window"));
                            SettingSuc_Button = GTK_WIDGET(gtk_builder_get_object(settingsuc_builder,"SettingSuc_Button"));
                            gtk_window_set_title (GTK_WINDOW (SettingFail_Window), "修改信息成功");
                            g_signal_connect(G_OBJECT(SettingSuc_Button),"clicked",G_CALLBACK(on_settingsuc_Button_clicked),NULL);
                            gtk_builder_connect_signals(settingsuc_builder,NULL);
                            g_object_unref(G_OBJECT(settingsuc_builder));
                            gtk_widget_show(SettingSuc_Window);
                            gtk_main();

                         }
                          pthread_cancel(Setting_Listenthread_t);






}


void *draw_msgreceived_image(void * user_data)
{
    int j,temp;
    clientRequest * tempmsg = (clientRequest *)user_data;
   //clientRequest offlinemsg = *((clientRequest)user_data);
    clientRequest offlinemsg =  *tempmsg;
    g_print("draw_msgreceived_image:%s \n",offlinemsg.senderName);


    g_print("test1 \n");
   /* for(j=0;j<user_num;j++)
    {   printf("teat2 \n");
        if(strcmp(offlinemsg.senderName,userinfo[j].senderName) ==0)
        {
            temp = j;
            printf("temp:%d \n",temp);
            break;
        }

    }
    */
    j = 0;
    while(j<user_num)
    {
        j++;
        g_print("teat2 \n");
        if(strcmp(offlinemsg.senderName,userinfo[j].senderName) ==0)
        {
            temp = j;
            printf("temp:%d \n",temp);
            break;
        }

    }


    user_window[temp].flag = 1;
    printf("%s :你的头像正在闪动 \n",user_window[temp].Name);
    printf("flag= %d \n",user_window[temp].flag);

    while(1)
    {
          gtk_widget_hide(image1[temp]);
          usleep(200000);
          gtk_widget_show(image1[temp]);
          usleep(200000);
    }
    return (void *)0;


}
/*void *recv_file( void *arg)
{
     execl("./LPFSupport","./LPFSupport","gf",(char * )0) ;
     return (void *)0;
}
*/
void *Mainframe_Listenthread(void *arg)
{
        int i = 0;
        int sock_len;
        char buf[1024];
        clientRequest whoisthis;
        struct sockaddr_in sockMainframe_listen_recv;

        bzero(&sockMainframe_listen_recv, sizeof(sockMainframe_listen_recv));
        sockMainframe_listen_recv.sin_family = AF_INET;
        sockMainframe_listen_recv.sin_addr.s_addr = INADDR_ANY;
        sockMainframe_listen_recv.sin_port = htons(PORT);
        sock_len = sizeof(sockMainframe_listen_recv);
        if((socket_mainframe_listen_recv = socket(AF_INET,SOCK_DGRAM,0)) == -1)                                                                     //接受注册成功/失败信息
        {
                perror("Socket_recv");
                exit(1);
        }
        else if (bind(socket_mainframe_listen_recv,(struct sockaddr *)&sockMainframe_listen_recv,sizeof(sockMainframe_listen_recv)) == -1)
        {
                printf("Error in bind\n");
                exit(1);
                close(socket_mainframe_listen_recv);
        }
        else
        {
                while(1)
                {

                        if (recvfrom(socket_mainframe_listen_recv,buf,sizeof(buf),0,(struct sockaddr*)&sockMainframe_listen_recv, (socklen_t *)&sock_len) != -1)
                        {
                            i = 0;
                            bzero(whoisthis.senderName,sizeof(whoisthis.senderName));
                            bzero(whoisthis.msg,sizeof(whoisthis.msg));
                            if(buf[0] == '2' || buf[0] == 'M')
                            {
                                if(chat_msg[i].Name[0] != '\0')
                                        i++;
                                whoisthis = Get_client_request(buf);
                                strcpy(chat_msg[i].Name, whoisthis.senderName);
                                strcpy(chat_msg[i].msg, whoisthis.msg);
                              //  int j = 0;
                              //  strcpy(user_window[j].Name, whoisthis.senderName);
                              //  j++;
                               if(i == 9)
                                        i = 0;
                                else
                                        i++;
                                int temp,j;
                                printf("user_num : %d",user_num);
                                for(j=0;j<user_num;j++)
                                {
                                    if(strcmp(user_window[j].Name,whoisthis.senderName) ==0)
                                    {
                                        temp = j;
                                        break;
                                    }

                                }
                                printf("j= %d temp=%d \n",j,temp);
                                printf("%s是你发过来的消息.\n",whoisthis.senderName);
                                printf("%s开始创建闪动线程了.\n",user_window[temp].Name);
                                printf("flag: %d \n",user_window[temp].flag);
                                //开画图线程
                                if(user_window[temp].flag == 0)//窗口没打开，创建闪动线程
                                     pthread_create(&drawimage_t,NULL,draw_msgreceived_image,(void *)&whoisthis);
                            }
                            i = 0;
                            if(buf[0] =='6')
                            {

                                //pthread_t recvfile_t;
                                 pid_t pid;
                                gchar filemessage[30];
                                if(chat_msg[i].Name[0] != '\0')
                                        i++;
                                whoisthis = Get_client_request(buf);
                                strcpy(chat_msg[i].Name, whoisthis.senderName);
                                g_print("接受文件的信息： %s \n",buf);
                                sprintf(filemessage,"%s 正在给你发送文件",whoisthis.senderName);
                                strcpy(chat_msg[i].msg, filemessage);
                                //pthread_create(&recvfile_t,NULL,recv_file,NULL);
                                 pid = fork();
                                 switch(pid)
                                {
                                    case -1:
                                    perror("fork failed");
                                    exit(1);
                                    case 0:
                                    execl("./LPFSupport","./LPFSupport","g",(char * )0) ;
                                    break;
                                    default:
                                    break;

                                }

                            }
                            i = 0;
                            if(buf[0] =='7')
                            {
                                 printf("哈哈，受到群消息了！ \n");
                                 printf("buf : %s",buf);
                                 if(gpchat_msg[i].Name[0] != '\0')
                                        i++;
                                whoisthis = Get_client_request(buf);
                                strcpy(gpchat_msg[i].Name, whoisthis.senderName);
                                strcpy(gpchat_msg[i].msg, whoisthis.msg);
                                strcpy(gpchat_msg[i].branch, whoisthis.branch);
                              //  int j = 0;
                              //  strcpy(user_window[j].Name, whoisthis.senderName);
                              //  j++;
                               if(i == 9)
                                        i = 0;
                                else
                                        i++;
                            }



                        }
                }
        }
        return (void *)0;
}


void on_selectimage_button_clicked(GtkObject *object,int *x)
{

    int yourtemp = *x;
    printf(" yourtemp = %d \n",yourtemp);
//  char imagepath[30];
 //   bzero(imagepath,sizeof(imagepath));

    myinformation.profilepic = yourtemp;
    printf("test\n");
    printf("头像序号： %d \n",myinformation.profilepic);

    gtk_widget_hide(imgsltwindow);
 //   sprintf(imagepath,"./smallface40/%d.bmp",yourtemp);
//    settingimage = gtk_image_new_from_file(imagepath);
 //   gtk_widget_show (settingimage);
 //   gtk_container_add (GTK_CONTAINER (Setting_Window), settingimage);
}
void show_image_select_window(GtkObject *object,gpointer user_data)
{

    GtkWidget *scrolledwindow;
   // GtkWidget *viewport;
  //  GtkWidget *table;
    int i=0;
    GtkWidget *fixed1;
    GtkWidget *button[36];
    GtkWidget *image[36];
    gchar imagepath[30];
    bzero(imagepath,sizeof(imagepath));

    imgsltwindow = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (imgsltwindow), ("选择头像"));
    gtk_window_set_default_size(GTK_WINDOW(imgsltwindow),500,400);

    scrolledwindow = gtk_scrolled_window_new(NULL,NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwindow),GTK_POLICY_AUTOMATIC,GTK_POLICY_AUTOMATIC);
    gtk_container_add(GTK_CONTAINER(imgsltwindow), scrolledwindow);

    fixed1 = gtk_fixed_new();
    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolledwindow), fixed1);




    for(i=0 ;i<36 ;i++)
    {
      ImageNo[i] = i;
      button[i] = gtk_button_new();
      gtk_fixed_put(GTK_FIXED(fixed1),button[i],(40+70*(i%6)),(25+70*(i/6)));
      gtk_widget_set_size_request(button[i], 60, 60);

      sprintf(imagepath,"./LittleFace/%d.bmp",i);
      image[i] = gtk_image_new_from_file(imagepath);
      gtk_container_add (GTK_CONTAINER (button[i]), image[i]);
      g_signal_connect(G_OBJECT(button[i]),"clicked",G_CALLBACK(on_selectimage_button_clicked),&ImageNo[i]);

    }

    gtk_widget_show_all(imgsltwindow);



}


void on_cancel_button_clicked(GtkObject *object,gpointer user_data)
{
        gtk_widget_hide(Setting_Window);
}
void on_Mainframe_SettingButton_clicked(GtkObject *object,gpointer user_data)
{
        GtkWidget *imageselect_btn;
        GtkWidget *settingimage;
        GtkWidget *cancelbutton;
        char myimagepath[30];
        Setting_builder = gtk_builder_new();
        gtk_builder_add_from_file(Setting_builder,"Setting.glade",NULL);

        Setting_Window = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"Setting_Window"));
        nickname = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"entry1"));
        Setting_GenderCBX = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"Setting_GenderCBX"));
        age = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"entry3"));
        Setting_BranchCBX = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"Setting_BranchCBX"));
        telephone = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"entry6"));
        birthday = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"entry7"));
        okbutton = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"okbutton"));
        imageselect_btn = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"imageselect_btn"));
        settingimage = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"settingimage"));
        cancelbutton = GTK_WIDGET(gtk_builder_get_object(Setting_builder,"button3"));
        bzero(myimagepath,sizeof(myimagepath));






        sprintf(myimagepath,"./NormalFace/%d.bmp",myinformation.profilepic);
        printf("myimagepath = %s",myimagepath);
        gtk_image_set_from_file(GTK_IMAGE(settingimage),myimagepath);
       // gtk_widget_show (settingimage);
      // gtk_container_add (GTK_CONTAINER (Setting_Window), settingimage);

        g_signal_connect(G_OBJECT(okbutton),"clicked",G_CALLBACK(modify_myinformation),NULL);
        g_signal_connect(G_OBJECT(imageselect_btn),"clicked",G_CALLBACK(show_image_select_window),NULL);
        g_signal_connect(G_OBJECT(cancelbutton),"clicked",G_CALLBACK(on_cancel_button_clicked),NULL);





    /*    gchar temp[NAMELEN];
        bzero(temp,sizeof(temp));

        gint index = 0;
        sprintf(temp, "%d", myinformation.age);
        if(myinformation.nickName[0] != '\0')
        {
              gtk_entry_set_text(GTK_ENTRY(nickname), myinformation.nickName);
        }
        if(myinformation.nickName[0] != '\0')
        {
//                gtk_entry_set_text(GTK_ENTRY(gender), myinformation.gender);
        }
        if(myinformation.nickName[0] != '\0')
        {
              gtk_entry_set_text(GTK_ENTRY(age), temp);
        }
        if(myinformation.nickName[0] != '\0')
        {
                gtk_entry_set_text(GTK_ENTRY(   GTK_OMBO))
        }
        if(myinformation.nickName[0] != '\0')
        {
              gtk_entry_set_text(GTK_ENTRY(telephone), myinformation.telephone);
        }
        if(myinformation.nickName[0] != '\0')
        {
              gtk_entry_set_text(GTK_ENTRY(birthday), myinformation.birthdate);
        }
*/


        gtk_builder_connect_signals(Setting_builder,NULL);
        g_object_unref(G_OBJECT(Setting_builder));
        gtk_widget_show_all(Setting_Window);
        gtk_main();

}


